<template>
  <md-page title="互动发布" isBtn :btnTextItems="[{ text: '提交发布', key: 'submit' }]" @btnClick="bottomBtnClick">
    <view class="container">
      <uni-forms ref="form" :modelValue="data.form" label-position="top" label-width="100">
        <uni-forms-item
          label="标题"
          name="title"
          required
          :rules="[
            {
              required: true,
              errorMessage: '请输入标题',
            },
          ]">
          <uni-easyinput type="text" v-model="data.form.title" placeholder="请输入标题" :input-border="false" />
        </uni-forms-item>
        <uni-forms-item
          label="内容"
          name="content"
          required
          :rules="[
            {
              required: true,
              errorMessage: '请输入内容',
            },
          ]">
          <uni-easyinput type="textarea" v-model="data.form.content" placeholder="请输入内容" :input-border="false" />
        </uni-forms-item>
        <uni-forms-item label="图片" name="imgs">
          <view class="image-wrap">
            <uni-file-picker limit="9" title="最多选择9张图片" file-mediatype="image" @select="handleUpload" />
          </view>
        </uni-forms-item>
      </uni-forms>
    </view>
  </md-page>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
// 接口
import { interactionCreate, uploadImage } from '@/api';
import type { Interaction } from '@/api/data';

const data = reactive<any>({
  form: {
    title: '',
    content: '',
    imgs: [],
  },
});
const form = ref(null);
const loading = ref(false);

// 提交按钮回调
const bottomBtnClick = async () => {
  try {
    const res = await form.value?.validate();
    fetchInteractionCreate({ ...res, imgs: res?.imgs.map((item: { url: string }) => item.url).join() });
  } catch (error) {}
};

/**
 * 上传相关
 */
const handleUpload = async (e: any) => {
  // console.log('选择文件：', e);
  let { tempFilePaths } = e;
  uni.showLoading({
    title: '图片上传中...',
    mask: true,
  });
  let uploadTasks = tempFilePaths.map(async (filePath: string) => {
    let res = await uploadImage({ filePath, formData: { category: 'interaction' } });
    const url = res.data.url;
    const name = url?.split?.('/')?.slice(-1);
    // 格式化组件需要的格式
    return {
      url,
      extname: 'png',
      name,
    };
  });
  Promise.all(uploadTasks).then(imgs => {
    uni.hideLoading();
    console.log('所有图片上传成功', imgs);
    data.form.imgs = imgs;
  });
};

/**
 * 接口相关
 */
const fetchInteractionCreate = async (params: Interaction.Create.Body) => {
  if (loading.value) {
    return;
  }
  try {
    loading.value = true;
    const res = await interactionCreate(params);
    uni.showModal({
      title: '提示',
      content: res.msg,
      showCancel: false,
      success: res => {
        if (res.confirm) {
          uni.navigateBack();
        }
      },
    });
  } catch (error) {}
  setTimeout(() => {
    loading.value = false;
  }, 500);
};
</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
  .image-wrap {
    background: white;
    padding: 10rpx 20rpx 20rpx;
  }
}
</style>
